<template>
  <div class="habits-container">
    <van-nav-bar title="习惯打卡" left-arrow @click-left="goBack" />
    
    <div class="content">
      <!-- 今日打卡概览 -->
      <div class="today-overview">
        <van-circle
          v-model:current-rate="completionRate"
          :rate="100"
          :speed="100"
          :text="completionText"
          size="120px"
          layer-color="#ebedf0"
          color="linear-gradient(135deg, #667eea 0%, #764ba2 100%)"
        />
        <div class="overview-stats">
          <div class="stat-item">
            <span class="stat-number">{{ completedCount }}</span>
            <span class="stat-label">已完成</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">{{ totalCount }}</span>
            <span class="stat-label">总习惯</span>
          </div>
        </div>
      </div>

      <!-- 习惯列表 -->
      <div class="habits-list">
        <van-cell-group title="今日习惯">
          <van-swipe-cell v-for="habit in todayHabits" :key="habit.id">
            <van-cell
              :title="habit.name"
              :label="habit.description"
              :value="habit.completed ? '已完成' : '待完成'"
              :class="{ 'completed-habit': habit.completed }"
            >
              <template #icon>
                <van-icon
                  :name="habit.icon"
                  size="24"
                  :color="habit.completed ? '#07c160' : '#969799'"
                  style="margin-right: 12px;"
                />
              </template>
              <template #value>
                <van-button
                  :type="habit.completed ? 'success' : 'primary'"
                  size="small"
                  @click="toggleHabit(habit)"
                >
                  {{ habit.completed ? '已完成' : '打卡' }}
                </van-button>
              </template>
            </van-cell>
            <template #right>
              <van-button
                square
                type="danger"
                text="删除"
                @click="deleteHabit(habit)"
              />
            </template>
          </van-swipe-cell>
        </van-cell-group>
      </div>

      <!-- 添加新习惯 -->
      <div class="add-habit-section">
        <van-button type="primary" block @click="showAddHabit = true">
          <van-icon name="plus" /> 添加新习惯
        </van-button>
      </div>

      <!-- 打卡历史 -->
      <div class="history-section">
        <van-cell-group title="本周打卡记录">
          <div class="week-calendar">
            <div class="week-day" v-for="day in weekDays" :key="day.date">
              <div class="day-name">{{ day.name }}</div>
              <div class="day-date">{{ day.date }}</div>
              <div class="day-progress">
                <van-circle
                  v-model:current-rate="day.completion"
                  :rate="100"
                  size="40px"
                  :text="day.completion + '%'"
                  layer-color="#ebedf0"
                  color="#07c160"
                />
              </div>
            </div>
          </div>
        </van-cell-group>
      </div>
    </div>

    <!-- 添加习惯弹窗 -->
    <van-dialog
      v-model:show="showAddHabit"
      title="添加新习惯"
      show-cancel-button
      @confirm="addHabit"
    >
      <van-field
        v-model="newHabit.name"
        label="习惯名称"
        placeholder="请输入习惯名称"
        required
      />
      <van-field
        v-model="newHabit.description"
        label="习惯描述"
        placeholder="请输入习惯描述"
        type="textarea"
        rows="2"
      />
      <van-field
        v-model="newHabit.icon"
        label="图标"
        placeholder="请选择图标"
        readonly
        @click="showIconPicker = true"
      />
      <van-field
        v-model="newHabit.frequency"
        label="频率"
        placeholder="请选择频率"
        readonly
        @click="showFrequencyPicker = true"
      />
    </van-dialog>

    <!-- 图标选择器 -->
    <van-popup v-model:show="showIconPicker" position="bottom">
      <van-picker
        :columns="iconOptions"
        @confirm="onIconConfirm"
        @cancel="showIconPicker = false"
      />
    </van-popup>

    <!-- 频率选择器 -->
    <van-popup v-model:show="showFrequencyPicker" position="bottom">
      <van-picker
        :columns="frequencyOptions"
        @confirm="onFrequencyConfirm"
        @cancel="showFrequencyPicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { habitApi } from '@/api/services'
import { initMqttClient, subscribeTopic, unsubscribeTopic, publishMessage } from '@/api/mqtt'

const router = useRouter()

// 基础数据
const completionRate = ref(0)
const completedCount = ref(0)
const totalCount = ref(0)
const showAddHabit = ref(false)
const showIconPicker = ref(false)
const showFrequencyPicker = ref(false)
const loading = ref(false)
const userId = ref(localStorage.getItem('userId') || '00000000-0000-0000-0000-000000000000')

// 新习惯数据
const newHabit = ref({
  name: '',
  description: '',
  icon: 'clock-o',
  frequency: '每天'
})

// 今日习惯列表
const todayHabits = ref([])

// 本周打卡数据
const weekDays = ref([
  { name: '一', date: '', completion: 0 },
  { name: '二', date: '', completion: 0 },
  { name: '三', date: '', completion: 0 },
  { name: '四', date: '', completion: 0 },
  { name: '五', date: '', completion: 0 },
  { name: '六', date: '', completion: 0 },
  { name: '日', date: '', completion: 0 }
])

// 选项数据
const iconOptions = [
  'clock-o', 'umbrella-circle-o', 'flower-o', 'gem-o', 'moon-o',
  'sun-o', 'star-o', 'heart-o', 'smile-o', 'music-o',
  'book-o', 'tv-o', 'phone-o', 'computer-o', 'bag-o'
]

const frequencyOptions = [
  '每天', '每周', '每月', '工作日', '周末'
]

// 计算属性
const completionText = computed(() => {
  return `${completionRate.value}%`
})

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    // 获取用户习惯数据
    const habitsResponse = await habitApi.getHabitsByUserId(userId.value)
    if (habitsResponse && habitsResponse.length > 0) {
      // 转换数据格式
      todayHabits.value = habitsResponse.map(habit => ({
        id: habit.id,
        name: habit.name,
        description: habit.description || '',
        icon: habit.icon || 'clock-o',
        completed: habit.isCompleted || false,
        target: habit.targetCount || 1,
        current: habit.currentCount || 0
      }))
      
      // 更新完成率
      updateCompletionRate()
    }
    
    // 初始化本周日期
    initializeWeekDays()
    
    // 获取本周打卡记录
    await fetchWeekRecords()
  } catch (error) {
    console.error('获取习惯数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 初始化本周日期
const initializeWeekDays = () => {
  const today = new Date()
  const currentDay = today.getDay() || 7 // 周日为7
  const monday = new Date(today)
  monday.setDate(today.getDate() - currentDay + 1)
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(monday)
    date.setDate(monday.getDate() + i)
    weekDays.value[i].date = `${String(date.getMonth() + 1).padStart(2, '0')}/${String(date.getDate()).padStart(2, '0')}`
  }
}

// 获取本周打卡记录
const fetchWeekRecords = async () => {
  try {
    // 这里应该调用获取本周记录的API，暂时模拟数据
    // const recordsResponse = await habitApi.getWeeklyRecords(userId.value)
    
    // 模拟数据
    weekDays.value.forEach(day => {
      day.completion = Math.floor(Math.random() * 100)
    })
  } catch (error) {
    console.error('获取本周记录失败:', error)
  }
}

// MQTT消息处理
const handleMqttMessage = (message) => {
  console.log('收到MQTT消息:', message)
  if (message.type === 'habit_update') {
    // 更新习惯数据
    if (message.habitId) {
      const habit = todayHabits.value.find(h => h.id === message.habitId)
      if (habit) {
        habit.completed = message.completed
        updateCompletionRate()
      }
    }
  }
}

// 初始化MQTT
const initMqtt = async () => {
  try {
    await initMqttClient()
    // 订阅用户专属主题
    subscribeTopic(`shelife/user/${userId.value}/habit_update`, handleMqttMessage)
  } catch (error) {
    console.error('MQTT初始化失败:', error)
  }
}

// 方法
const goBack = () => {
  router.back()
}

const toggleHabit = async (habit) => {
  try {
    // 更新UI状态
    habit.completed = !habit.completed
    if (habit.completed) {
      habit.current = habit.target
    } else {
      habit.current = 0
    }
    
    // 调用API更新习惯状态
    await habitApi.updateHabit({
      id: habit.id,
      userId: userId.value,
      name: habit.name,
      description: habit.description,
      icon: habit.icon,
      frequency: '每天',
      targetCount: habit.target,
      currentCount: habit.current,
      isCompleted: habit.completed
    })
    
    // 发布MQTT消息
    publishMessage(`shelife/user/${userId.value}/habit_update`, {
      type: 'habit_update',
      habitId: habit.id,
      completed: habit.completed,
      timestamp: new Date().toISOString()
    })
    
    // 更新完成率
    updateCompletionRate()
    
    showToast(habit.completed ? '打卡成功' : '取消打卡')
  } catch (error) {
    // 恢复UI状态
    habit.completed = !habit.completed
    console.error('更新习惯状态失败:', error)
    showToast('操作失败，请重试')
  }
}

const deleteHabit = async (habit) => {
  try {
    // 调用API删除习惯
    await habitApi.deleteHabit(habit.id)
    
    // 从列表中移除
    const index = todayHabits.value.findIndex(h => h.id === habit.id)
    if (index > -1) {
      todayHabits.value.splice(index, 1)
      updateCompletionRate()
    }
    
    showToast('习惯已删除')
  } catch (error) {
    console.error('删除习惯失败:', error)
    showToast('删除失败，请重试')
  }
}

const addHabit = async () => {
  if (!newHabit.value.name.trim()) {
    showToast('请输入习惯名称')
    return
  }
  
  try {
    // 准备保存的数据
    const habitData = {
      userId: userId.value,
      name: newHabit.value.name,
      description: newHabit.value.description,
      icon: newHabit.value.icon,
      frequency: newHabit.value.frequency,
      targetCount: 1,
      currentCount: 0,
      isCompleted: false
    }
    
    // 调用API创建习惯
    const savedHabit = await habitApi.createHabit(habitData)
    
    // 添加到列表
    const habit = {
      id: savedHabit.id,
      name: savedHabit.name,
      description: savedHabit.description || '',
      icon: savedHabit.icon || 'clock-o',
      completed: savedHabit.isCompleted || false,
      target: savedHabit.targetCount || 1,
      current: savedHabit.currentCount || 0
    }
    
    todayHabits.value.push(habit)
    resetNewHabit()
    updateCompletionRate()
    
    showToast('习惯添加成功')
  } catch (error) {
    console.error('添加习惯失败:', error)
    showToast('添加失败，请重试')
  }
}

const resetNewHabit = () => {
  newHabit.value = {
    name: '',
    description: '',
    icon: 'clock-o',
    frequency: '每天'
  }
}

const onIconConfirm = (value) => {
  newHabit.value.icon = value
  showIconPicker.value = false
}

const onFrequencyConfirm = (value) => {
  newHabit.value.frequency = value
  showFrequencyPicker.value = false
}

const updateCompletionRate = () => {
  const completed = todayHabits.value.filter(h => h.completed).length
  const total = todayHabits.value.length
  completedCount.value = completed
  totalCount.value = total
  completionRate.value = total > 0 ? Math.round((completed / total) * 100) : 0
}

// 生命周期钩子
onMounted(() => {
  initData()
  initMqtt()
})

onUnmounted(() => {
  // 清理MQTT订阅
  unsubscribeTopic(`shelife/user/${userId.value}/habit_update`, handleMqttMessage)
})
</script>

<style scoped lang="scss">
.habits-container {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 20px;
}

.content {
  padding: 0 16px;
}

.today-overview {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin: 16px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.overview-stats {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .stat-number {
    font-size: 24px;
    font-weight: bold;
    color: #333;
  }
  
  .stat-label {
    font-size: 12px;
    color: #999;
    margin-top: 2px;
  }
}

.habits-list {
  margin-bottom: 16px;
}

.completed-habit {
  background: #f0f9ff;
}

.add-habit-section {
  margin: 16px 0;
}

.history-section {
  margin-top: 16px;
}

.week-calendar {
  display: flex;
  justify-content: space-between;
  padding: 16px;
  background: white;
  border-radius: 12px;
}

.week-day {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  
  .day-name {
    font-size: 12px;
    color: #999;
  }
  
  .day-date {
    font-size: 10px;
    color: #666;
  }
}
</style>